import { hash } from "ph-utils/crypto_node";
import { random } from "ph-utils";

/**
 * 将分页数据转换为数据分页 的 limit, offset
 *
 * @param [page] {number|string} - 页码
 * @param [pageSize] {number|string} - 每一页数据
 * @returns
 */
export function pageLimit(page?: number | string, pageSize?: number | string) {
  const p = Number(page || 1);
  const ps = Number(pageSize || 10);
  return {
    page: p,
    pageSize: ps,
    limit: ps,
    offset: (p - 1) * ps,
  };
}

/**
 * 校验授权回调地址
 * @param {string} redirectUri 授权回调地址
 * @param {string} callbackUri 注册时的回调地址
 * @returns
 */
export function checkRedirectUri(
  redirectUri?: string | null,
  callbackUri?: string | null,
) {
  if (!redirectUri && !callbackUri) {
    return { code: 100101 };
  }

  if (!redirectUri) {
    return { code: 0, uri: callbackUri };
  }
  const redirectUrl = new URL(redirectUri);
  if (
    redirectUrl.hostname === "localhost" ||
    redirectUrl.hostname === "127.0.0.1"
  ) {
    return { code: 0, uri: redirectUri };
  }
  if (!callbackUri) {
    return { code: 100102 };
  }
  const callbackUrl = new URL(callbackUri);
  if (
    (callbackUrl.protocol !== redirectUrl.protocol ||
      callbackUrl.host !== redirectUrl.host) &&
    redirectUrl.hostname !== "localhost" &&
    redirectUrl.hostname !== "127.0.0.1"
  ) {
    return { code: 100103 };
  }
  return { code: 0, uri: redirectUri };
}

type AccessTokenInfo = {
  accessToken: string;
  refreshToken: string;
};

/**
 * 生成access_token, refresh_token
 * @param {string|number} idOrUserid
 * @returns {AccessTokenInfo}
 */
export function generateAccesstoken(
  idOrUserid: string | number,
): AccessTokenInfo {
  const accessToken = hash(`${idOrUserid}:${random(4)}:${Date.now()}`, "sha1");
  const refreshToken = hash(`${idOrUserid}:${random(6)}:${Date.now()}`, "sha1");
  return {
    accessToken,
    refreshToken,
  };
}
